package cn.group7.padserver.handler.authentication;

import cn.group7.padserver.common.Flag;
import cn.group7.padserver.controller.responseformat.Code;
import cn.group7.padserver.controller.responseformat.Result;
import cn.group7.padserver.utils.JwtTokenUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 谷汉斌
 * @description 登录成功处理器
 * @createTime 2024/7/31 下午3:47
 */
@Slf4j
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        //将token放入请求头中
        renderToken(httpServletResponse, token);
        log.info("用户{}登录成功！", userDetails.getUsername());
    }

    /**
     * 渲染返回 token 页面,因为前端页面接收的都是Result对象，故使用application/json返回
     *
     * @param response 响应
     * @throws IOException 异常
     */
    public void renderToken(HttpServletResponse response, String token) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        Result result = Result.builder()
                .flag(Flag.SUCCESS.isCode())
                .code(Code.LOGIN_SUCCESS.getCode())
                .data(token)
                .message(Code.LOGIN_SUCCESS.getInfo()).build();
        String s = JSON.toJSONString(result);
        out.write(s.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}